package org.esisar.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;

import org.esisar.model.Model;
import org.esisar.model.Orders;

public class OrdersStatementCreator implements StatementCreator{


	private PreparedStatement preparedStatement;
	
	@Override
	public PreparedStatement addStatement(Connection connection, Model model) throws SQLException {
		
		Orders order = modelToOrder(model);
			
		preparedStatement = connection.prepareStatement("INSERT INTO orders (idOrder,orderDate,idClient,idAddress) VALUES(orders_sequence.nextval,?,?,?)");

		fillModel(order);
	
		return preparedStatement;
		
	}

	@Override
	public PreparedStatement deleteStatement(Connection connection, List<Long> keys) throws SQLException {

		preparedStatement = connection.prepareStatement("DELETE FROM orders WHERE idOrder=?");

		preparedStatement.setLong(1, keys.get(0));
				
		return preparedStatement;
	}

	@Override
	public PreparedStatement updateStatement(Connection connection, Model model)
			throws SQLException {
		
		Orders order = modelToOrder(model);
		
		preparedStatement = connection.prepareStatement("UPDATE orders SET orderDate = ?, idClient = ?, idAddress = ? WHERE idOrder = ?");

		fillModel(order);
		preparedStatement.setString(4, order.getIdOrder() + "");
		
		return preparedStatement;
	}

	private void fillModel(Orders order) throws SQLException {
		preparedStatement.setDate(1, new java.sql.Date(order.getOrderDate().getTime()));
		preparedStatement.setString(2, order.getIdClient() + "");
		preparedStatement.setString(3, order.getIdAddress() + "");
	}

	private Orders modelToOrder(Model model) {
		Orders order;
		
		if (model instanceof Orders){
			order = (Orders) model;
		}else{
			throw new ClassCastException("Bad object instance");
		}
		return order;
	}
	
	@Override
	public PreparedStatement readStatement(Connection connection, String field,
			String value) throws SQLException {
		preparedStatement = connection.prepareStatement("select * from orders where " + field + " = ? ");

		preparedStatement.setString(1, value);
		
		return preparedStatement;
	}

	@Override
	public Model fillModel(ResultSet rs) throws SQLException {
		String idOrder = rs.getString("idOrder");
		Date orderDate = rs.getDate("orderDate");
		String idClient = rs.getString("idClient");
		String idAddress = rs.getString("idAddress");
		
		Orders order = new Orders(orderDate, Long.parseLong(idClient), Long.parseLong(idAddress));
		order.setIdOrder(Long.parseLong(idOrder));
		
		return order;
	}
	
}


